import random
import time
import traceback
import pymongo
import redis
import requests
from faker import Faker


def check_login(cookies, proxy):
    faker = Faker(locale='zh_CN')
    ip = faker.ipv4()
    headers = {
        'User-Agent': faker.chrome(),
        'CLIENT-IP': ip,
        'X-FORWARDED-FOR': ip,
        'Cookie': cookies
    }
    sess = requests.Session()
    sess.get("http://www.189.cn/dqmh/userCenter/myOrderInfoList.do?method=listMyOrderInfo_new&date_area=&status_type=&order_type=orders_recharge&pageNo=1&isVs=no", timeout=5)
    rsp = sess.get('http://www.189.cn/login/index.do', headers=headers, proxies=proxy, timeout=5)
    res = rsp.json()
    nickname = res['dataObject'].get('nickName')
    if not nickname:
        return {"code": "1", "message": "登录失效"}
    else:
        return res


if __name__ == '__main__':
    conn = redis.Redis(db=0)
    client = pymongo.mongo_client.MongoClient('mongodb://cs_user:cmcc5188@localhost:12018/cs_recharge')
    db = client.cs_recharge
    coll = db.cmcc_username
    # print(reg_confirm3('wur7910', 'aa7788'))

    #
    while True:
        objs = coll.find({"cookies": {"$ne": None}})
        for obj in objs:
            # pool.apply_async(main, (obj,))
            proxies = conn.smembers('un_proxy')
            proxy = random.choice([i.decode() for i in proxies if i and b'@' not in i])
            proxy = {"http": proxy}
            try:
                res = check_login(obj['cookies'], proxy)
                if res['code'] != "0":
                    # print(obj['username'], res)
                    conn.lrem("ctcc_user", obj['username'])
                    coll.update_one(obj, {"$set": {"cookies": None}})
                print(obj['username'], res)
            except Exception:
                traceback.print_exc()
        print("==================")
        time.sleep(60)
